package com.team.six.bluecatshop.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.team.six.bluecatshop.domain.*;
import com.team.six.bluecatshop.mapper.ProductMapper;
import com.team.six.bluecatshop.mapper.SkuMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SkuServiceImpl implements SkuService {
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    @Transactional
    public void add(Sku sku) {
        skuMapper.insert(sku);
    }

    @Override
    @Transactional
    public void remove(String id) {
        skuMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Sku findById(String id) {
        Sku sku=skuMapper.selectByPrimaryKey(id);
        return sku;
    }

    @Override
    public List<Sku> findAll() {
        List<Sku> skuList = skuMapper.findAll();
        return skuList;
    }

    @Override
    public List<Sku> findSkuByProductId(String id) {
        List<Sku> sku = skuMapper.findByProductId(id);
        return sku;
    }


    @Override
    @Transactional
    public void updateByPrimaryKey(Sku sku) {
        skuMapper.updateByPrimaryKeySelective(sku);
    }

    @Override
    public SeachSkuResponse findSkuAll(Integer pageNum, Integer pageSize, String keyword) {
        PageHelper.startPage(pageNum,pageSize);
        SkuExample example = new SkuExample();
        example.createCriteria().andSkuIdLike("%"+keyword+"%");
        List<Sku> skus = skuMapper.selectByExample(example);
        for (Sku sku : skus){
            //System.out.println(sku.getProductId());
            Product product = productMapper.selectByPrimaryKey(sku.getProductId());
            //System.out.println(product.getProductName());
            sku.setProductName(product.getProductName());
        }
        return new SeachSkuResponse(((Page)skus).getTotal(),skus);
    }
}
